<template>
  <div class="popup">
    <van-search 
      @search="onSearch"
      @cancel="$router.push('/category')"
      v-model="keyword" 
      show-action
      shape="round"
      background="white" 
      placeholder="请输入您想要的商品！"/>

     <div class="content">
        <div v-if="flag">
          <TagListVue :title="'最近搜索'" :tagList="historySearchList"></TagListVue>
          <TagListVue></TagListVue>
        </div>
        <div v-else>
          <SearchListVue ref="searchList" :productList="productList"></SearchListVue>
        </div>
     </div>
  </div>
</template>

<script>
import TagListVue from '../components/search/TagList.vue';
import SearchListVue from '../components/search/SearchList.vue';
import {search} from '@/request/api.js'
export default {
  components:{ TagListVue , SearchListVue },
  data(){
    return({
      flag:true,
      keyword:'',
      tagList:[
        'hhh',
        'fff',
        'dfsaf',
        'sadf'
      ],
      productList:[],
      historySearchList: []
    })
  },
  watch:{
    keyword(newVal,oldVal){
      if(newVal == '') this.flag = true
    },
  },
  mounted(){
    if(localStorage.getItem('historySearchList')) this.historySearchList = JSON.parse(localStorage.getItem('historySearchList'))
  },
  methods:{
    onSearch(){
      this.flag = false
      this.historySearchList.push(this.keyword)
      this.historySearchList = this.historySearchList.filter((item,index)=>this.historySearchList.indexOf(item)===index)
      localStorage.setItem('historySearchList',JSON.stringify(this.historySearchList))
      this.$nextTick(()=>{
        let {sort,type} = this.$refs.searchList
        let data = {keyword:this.keyword,sort,type}
        search(data).then(res=>{
          this.productList = res.data
        })
      })
    },
  }
}
</script>

<style scoped>
.content{
  background: #fff;
  min-height:calc(100vh - 56px);
  box-sizing: border-box;
}
</style>